<template>
  <div class="login-container">
    <el-form
      :rules="rules"
      :model="ruleForm"
      ref="ruleForm"
      label-width="100px"
      class="demo-dynamic"
    >
      <el-form-item prop="telephone" label="手机号码">
        <el-input v-model="ruleForm.telephone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="register()">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    var validateTelephone = (rule, value, callback) => {
      const reg = /^[1][3|4|5|6|7|8|9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };

    return {
      ruleForm: {
        telephone: "",
        pass: ""
      },
      rules: {
        telephone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: validateTelephone, trigger: "blur" }
        ],
        pass: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      const _this = this;
      console.log("提交", _this.ruleForm);
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$axios
            .get("/user/login", {
              params: {
                telephone: _this.ruleForm.telephone,
                password: _this.ruleForm.pass
              }
            })
            .then(function(res) {
              if (res.status == 200) {
                window.localStorage.setItem(
                  "userInfo",
                  JSON.stringify(res.data)
                );
                alert("登录成功");
                _this.$router.push("/");
              } else {
                alert("账号或密码不正确！");
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    register() {
      this.$router.push("/register");
    }
  }
};
</script>

<style scoped>
.login-container {
  width: 40%;
  min-width: 300px;
  height: 300px;
  margin: 35px auto;
}
</style>
